import 'dart:io';
import 'dart:convert';
void main() async {
//https://dart.cn/libraries/dart-io/#reading-a-file-as-text
  var config = File('config.txt');
  // Put the whole file in a single string.
  var stringContents = await config.readAsString();
  print('The file is ${stringContents.length} characters long.');

  // Put each line of the file into its own string.
  var lines = await config.readAsLines();
  print('The file is ${lines.length} lines long.');


//https://dart.cn/libraries/dart-io/#reading-a-file-as-binary


var config01 = File('config.txt');
  var contents = await config01.readAsBytes();
  print('The file is ${contents.length} bytes long.');


//https://dart.cn/libraries/dart-io/#handling-errors

 var config02 = File('config.txt');
  try {
    var contents = await config02.readAsString();
    print(contents);
  } catch (e) {
    print(e);
  }


//https://dart.cn/libraries/dart-io/#streaming-file-contents

  var config03 = File('config.txt');
  Stream<List<int>> inputStream = config03.openRead();

  var lines01 = utf8.decoder.bind(inputStream).transform(const LineSplitter());
  try {
    await for (final line in lines01) {
      print('Got ${line.length} characters from stream');
    }
    print('file is now closed');
  } catch (e) {
    print(e);
  }




//https://dart.cn/libraries/dart-io/#writing-file-contents

var logFile = File('log.txt');
var sink = logFile.openWrite();
sink.write('FILE ACCESSED ${DateTime.now()}\n');
await sink.flush();
await sink.close();




//https://dart.cn/libraries/dart-io/#listing-files-in-a-directory
var dir = Directory('tmp');
// 检查目录是否存在
  if (!await dir.exists()) {
    // 创建目录
    await dir.create();
    print('目录 tmp 已创建！');
  } else {
    print('目录 tmp 已存在！');
  }
  try {
    var dirList = dir.list();
    await for (final FileSystemEntity f in dirList) {
      if (f is File) {
        print('Found file ${f.path}');
      } else if (f is Directory) {
        print('Found dir ${f.path}');
      }
    }
  } catch (e) {
    print(e.toString());
  }



//https://dart.cn/libraries/dart-io/#http-server
final requests = await HttpServer.bind('localhost', 8888);
  await for (final request in requests) {
    processRequest(request);
  }

}

//https://dart.cn/libraries/dart-io/#http-server
void processRequest(HttpRequest request) {
  print('Got request for ${request.uri.path}');
  final response = request.response;
  if (request.uri.path == '/dart') {
    response
      ..headers.contentType = ContentType('text', 'plain')
      ..write('Hello from the server');
  } else {
    response.statusCode = HttpStatus.notFound;
  }
  response.close();
}










